//################################
// 版权所有：鸽子游戏俱乐部
// 系统名称：鸽子游戏俱乐部-移动版
// 文件名称：commonFunc.js
// 创建时间：2016年06月29日
// 创建人员：Lemo
// 功能说明：公共函数类
//################################

'use strict';

import * as Constants from './uiconstants';
import Config from './config';
import Routes from './routes';
import Immutable from 'immutable';

import flattenStyle from 'flattenStyle';

var deepCopy = function(source){
    var result={};
    for (var key in source) {
        if( source[key] ){
            if ( isArray( source[key] ) ){
                result[key] = deepCopyList( source[key] )
            }else{
                result[key] = Object.prototype.toString.call(source[key]) === "[object Object]"? deepCopy(source[key]): source[key];
            }
        }else{
            result[key] = source[key];
        }
       
          
    }
    return result;
}

var deepCopyList = function(array){
        var result = [];

        if( isArray(array) ){
           result = array.map((item) => {
               if( isArray(item) ){
                    return deepCopyList( item )
               }else{                 
                   return deepCopy( item )
               }
              
           })
           return result
        }
        return [];
}

var isArray = function(array){
    if (typeof Array.isArray === "function") {
        return Array.isArray(array);
    }else{
        return Object.prototype.toString.call(array) === "[object Array]";
    }
}

Array.prototype.indexOf = function(val) {              
    for (var i = 0; i < this.length; i++) {  
        if (this[i] == val) return i;  
    }  
    return -1;  
};

Array.prototype.remove = function(val) {  
    var index = this.indexOf(val);  
    if (index > -1) {  
        this.splice(index, 1);  
    }  
}; 

Array.prototype.contains = function(val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) {
            return true;
        }
    }
    return false;
};

Array.prototype.insert = function(index, item) {
    this.splice(index, 0, item);
}

String.prototype.startWith=function(str){ 
    var reg=new RegExp("^"+str); 
    return reg.test(this); 
} 

String.prototype.endWith=function(str){ 
    var reg=new RegExp(str+"$"); 
    return reg.test(this); 
} 

module.exports = {
	// 判空函数
	isEmpty: function(obj){
        var tmp = Object.prototype.toString.call(obj);
        if( tmp === '[object Undefined]' || tmp === '[object Null]' ){
            return true;
        }

        if( tmp === '[object String]' ){
            return obj == '';
        }else if( tmp === '[object Object]' ){
            for( var key in obj ){
				return false;
			}
			return true;
        }else if( tmp === '[object Array]' ){
            return obj.length == 0;
        }
	},
	deepCopy : deepCopy,

    // deepCopyList : function(array){
    //     var result = [];

    //     if( isArray(array) ){
    //         for(var i = 0; i < array.length; i ++){
    //             result[i] = deepCopy( array[i] );
    //         }
    //         return result;
    //     }
    //     return [];
    // },
    deepCopyList : deepCopyList,
    // 从数组array中查找是否存在str
    containsStr: function(array, str){
        if( array.length == 0 ){
            return false;
        }
        for( var i = 0; i < array.length; i++ ){
            if( array[i] == str ){
                return true;
            }
        }
        return false;
    },

    // 从数组array中查找是否存在str
    getFontSizeFromStyle: function(style){
        // if(style && Object.prototype.toString.call( style ) === "[object Number]"){
            style = flattenStyle(style);
        // }
        if( style && isArray( style )){
            for( var i = 0; i < style.length; i++ ){
                if( style[i] && style[i].fontSize ){
                    return style[i]['fontSize'];
                }
            }
        }
        if( style && Object.prototype.toString.call( style ) === "[object Object]"){
            return style.fontSize;
        }
        return 12;
    },

    // 给数字 number添加总位数为totalLen的前导零
    addLeadingZeros: function(totalLen, number){
        var numberType = Object.prototype.toString.call(number);
        var lenType = Object.prototype.toString.call(totalLen);
        var res = '';
        if( numberType === '[object String]' &&  lenType === '[object Number]' ){
            var lenTmp = totalLen - number.length;
            for( var i = 0; i < lenTmp; i++ ){
                res += '0';
            }
            res += number;
        }
        return res;
    },

    // 返回公文类型，通过 英文单词映射
    getSOIType: function(type){
        var characArrays = ['', '规划及制度类', '一般业务类'];
        var engArrays = ['nothing', 'institution', 'ordinary'];

        for( var i = 0; i < engArrays.length; i++ ){
            if( engArrays[i] == type ){
                return characArrays[i];
            }
        }
        return '';
    },

    // 返回公文流水编号，通过 flddoctype确定
    getSOILiushuiNumber: function(type){
        switch (type) {
            case '党委':
                return 'DW';
            case '行政':
                return 'XZ';
            case '其他':
                return 'QT';
            default:
                return '';
        }
    },

    getShortNotesId: function(srcStr){
        if(srcStr){
            return srcStr.replace(/OU=/g,'').replace(/CN=/g,'').replace(/O=/g,'').replace(/@ABC/g,'');
        }else{
            return srcStr;
        }
    },

    getUserNameFromAddress:function(srcStr){
        var pattern1 = /\/ABC$/;
        var pattern2 = /^([a-zA-Z0-9_\-\.])+@(([a-zA-Z0-9_\-])+\.)+([a-zA-Z0-9_\-])+$/;
        //增加<>形式判断
        var pattern3 = /^[^\<\>]*(\<([a-zA-Z0-9_\-\.])+@(([a-zA-Z0-9_\-])+\.)+([a-zA-Z0-9_\-])+\>)/;

        if(pattern2.test(srcStr)){
            let idx = srcStr.indexOf('@');
            return srcStr.substring(0,idx);
        }else if(pattern3.test(srcStr)){
            let idx = srcStr.indexOf('<');
            let atIdx = srcStr.indexOf('@');
            let name = srcStr.substring(0,idx);
            if(name.trim()){
                return name;
            }else{
                return srcStr.substring(idx+1,atIdx);
            }//end of if
        }else{
            return this.getUserNameFromNotes(srcStr);
        }//end of if
    },//end of getUserNameFromAddress

    getUserNameFromNotes: function(srcStr){
        if(srcStr && typeof srcStr ==='string'){
            var idx = srcStr.indexOf('/');
            if( idx != -1 ){
                srcStr = srcStr.substring(0, idx);
            }
            idx = srcStr.indexOf('CN=');
            if( idx != -1 ){
                srcStr = srcStr.substring(idx+3);
            }
            return srcStr;
        }else{
            return srcStr;
        }
    },

    isArray : function(value){
        if (typeof Array.isArray === "function") {
            return Array.isArray(value);
        }else{
            return Object.prototype.toString.call(value) === "[object Array]";
        }
    },
    /**
    获取服务器配置
    */
    getServerConfig: function(key){
        return Config[key];
    },
    /**
     * 设置服务器配置
     */
    setServerConfig: function(key, val){
        Config[key] = val;
    },
    /**
    获取URL配置
    */
    getUrlConfig: function(key, type){
        return Config['urls'][type][key];
    },
    /**
    获取文字
    */
    getText: function(key){
        return Constants['tips'][key];
    },
    /**
    获取常量
    */
    getConstants: function(key){
        return Constants['consts'][key];
    },
    setConstants: function(key, value){
        return Constants['consts'][key] = value;
    },
    inArray: function(array, object) {
        for (var i=0;i<array.length;i++) {
            if (array[i] == object) return i;
        }
        return -1;
    },
    getCommonData: function(key){
        return CommonData[key];
    },
    setCommonData: function(key, value){
        CommonData[key] = value;
    },
    getFileSizeStr : function( byte ){
        if( !byte || !Object.prototype.toString.call( byte ) === "[object Number]"){
            return '';
        }
        let result = '';
        let yushu = byte % 1024;//余数
        let kStr = byte / 1024;//商值
        if( kStr > 1024 ){
            let mStr =  kStr / 1024 ;
            mStr = mStr.toFixed(1);
            return mStr  + 'M';
        }else{
            kStr = kStr.toFixed(1);
            return kStr + 'K';
        }
    },
    //格式化日期
    formatDate: function(rawDate,pattern){
        var o = {   
            "M+" : rawDate.getMonth()+1,                 //月份   
            "d+" : rawDate.getDate(),                    //日   
            "h+" : rawDate.getHours(),                   //小时   
            "m+" : rawDate.getMinutes(),                 //分   
            "s+" : rawDate.getSeconds(),                 //秒   
            "q+" : Math.floor((rawDate.getMonth()+3)/3), //季度   
            "S"  : rawDate.getMilliseconds()             //毫秒   
        };   
        if(/(y+)/.test(pattern)){
            pattern=pattern.replace(RegExp.$1, (rawDate.getFullYear()+"").substr(4 - RegExp.$1.length));   
        }
        for(var k in o){
            if(new RegExp("("+ k +")").test(pattern)){
                pattern = pattern.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
            } 
        }
        return pattern;   
    },//end of formatDate

    //字符串转日期
    stringToDate:function(dateStr,pattern){
        if(dateStr===null||dateStr===undefined){
            return;
        }
        dateStr=dateStr.replace(/-/g,"/");
        if(dateStr.indexOf('.')>=0){
            dateStr=dateStr.split('.')[0];
        }
        let newDate=new Date(dateStr);
        return this.formatDate(newDate,pattern);
    },

    getArrayFromObjProps(obj) {
        var array = [];

        for (var p in obj) {
            if (typeof(obj[p]) === 'function') {

            }
            else {
                array.push(obj[p]);
            }
        }

        return array;
    },
    isInArray(array, value) {
        var found = false;

        if (array && array.length && array.length > 0) {
            for (var i = 0;i < array.length;i++) {
                if (array[i] === value) {
                    found = true;
                    break;
                }
            }
        }

        return found;
    },
    isPageAtStackTop(routeName, routes) {
        //no longer used in soi, removed in the future
        let index = routes.length - 1;

        for (let i = index; i >= 0;i--) {
            if (routes[i].name.indexOf(Routes.ZHSOI_DETAIL) >= 0) {
                index = i;
                break;
            }else if(routes[i].name.indexOf(Routes.SOI_DETAIL) >= 0){
                index = i;
                break;
            }
        }

        return routeName === routes[index].name;
    },
    isSameSoi(oldSoiData,newSoiData){
        // return oldSoiData.navDocId === newSoiData.navDocId &&
        // oldSoiData.navDocId === null &&
        // newSoiData.navDocId === null &&
        // oldSoiData.id === newSoiData.id;

        if (oldSoiData.navDocId === null) {
            //该公文为依据公文
            if (newSoiData.navDocId === null) {
                return oldSoiData.id === newSoiData.id;
            }
            else {
                return false;
            }
        }
        else {
            return oldSoiData.navDocId === newSoiData.navDocId;
        }
    },
    getCommentReply : function( reply, creatorName, oldStr ){
        let id = "<div class=quoteList><div class=quoteItem>引用<span class=fontColorOrange>" + creatorName + "</span>的意见：<span><p class=wordBreak>";
        let result ='<div class=suggestionContent><p class=wordBreak>' + reply + '</p></div>' + id + oldStr + '</p></span></div></div>' ;
        return result;
    },
    mergeNewAndOldList:function(newList,oldList){
        if(oldList===null||oldList.length===0){
            return newList;
        }
        let index=-1;
        for (var i = 0;i < newList.length;i++) {
            if(newList[i].id===oldList[0].id){
                index=i;
                break;
            }
        }
        if (index !== -1) {
            let newItems=newList.slice(0, index);
            let finalList=newItems.concat(oldList);
            return finalList;
        }
        return oldList;
    },
    intersectList:function(newList,oldList){
        if(oldList===null||oldList.length===0){
            return [];
        }
        let index=-1;
        let item=newList[newList.length-1];
        for (var i = 0;i < oldList.length;i++) {
            if(oldList[i].id===item.id){
                index=i;
                break;
            }
        }
        if(index!==-1){
            let newItems=oldList.slice(index+1);
            let finalList=newList.concat(newItems);
            return finalList;
        }
        return newList;
    },
    isSameList(newList, oldList) {
        let newListImmutable = Immutable.List();
        let oldListImmutable = Immutable.List();

        for (let i = 0;i < newList.length;i++) {
            newListImmutable = newListImmutable.push(Immutable.Map(newList[i]));
        }

        if (oldList && oldList.length) {
            for (let i = 0;i < oldList.length;i++) {
                oldListImmutable = oldListImmutable.push(Immutable.Map(oldList[i]));
            }
        }

        return Immutable.is(newListImmutable, oldListImmutable);
    },
    removeDuplicatedItem(ar) {
        var tmp = {},
            ret = [];

        for (var i = 0, j = ar.length; i < j; i++) {
            if (!tmp[ar[i]]) {
                tmp[ar[i]] = 1;
                ret.push(ar[i]);
            }
        }

        return ret;
    },
    removeDuplcatedItem2(a, b) {
        for (let i = 0; i < a.length; i++) {
            let item = a[i];
            b.remove(item);
        }
        alert(b);
    },
    getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var seperator2 = ":";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
                + " " + date.getHours() + seperator2 + date.getMinutes()
                + seperator2 + date.getSeconds();
        return currentdate;
    },
    getTodayDate() {
        var date = new Date();
        var seperator1 = "/";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate;
        return currentdate;
    }
};